/**
 * Created on 2018年7月20日 by caiming
 */
package com.netty.fileupload.server;

import java.net.InetSocketAddress;

import com.fastDFS.FastDFSTemplate;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;

/**
 * @author caiming
 * @version 1.0
 * @Title
 * @Description
 * @修改记录
 * @修改序号，修改日期，修改人，修改内容
 */
public class WebSocketServer {

    private final ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

    private final EventLoopGroup group = new NioEventLoopGroup();

    private Channel channel1;

    private FastDFSTemplate fastDFSTemplate;

    public WebSocketServer(FastDFSTemplate fastDFSTemplate) {
        this.fastDFSTemplate = fastDFSTemplate;
    }

    public ChannelFuture start(InetSocketAddress address) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group).channel(NioServerSocketChannel.class).childHandler(createInitializer(channelGroup));
        ChannelFuture future = bootstrap.bind(address);
        future.syncUninterruptibly();
        channel1 = future.channel();
        return future;
    }

    protected ChannelInitializer<Channel> createInitializer(ChannelGroup channelGroup) {
        return new WebSocketServerInitializer(fastDFSTemplate);

    }

    public void destroy() {
        if (channel1 != null) {
            channel1.close();
        }
        channelGroup.close();
        group.shutdownGracefully();
    }

//	public static void main(String args[]) throws Exception {
//		int port = 9999;
//		final WebSocketServer endpoint = new WebSocketServer();
//		ChannelFuture future = endpoint.start(new InetSocketAddress(port));
//		Runtime.getRuntime().addShutdownHook(new Thread() {
//			public void run() {
//				endpoint.destroy();
//			}
//		});
//
//		future.channel().closeFuture().syncUninterruptibly();
//
//	}

}
